﻿using System;
using System.Data.SqlClient;
using System.Diagnostics;

namespace SQLDeploy.Data.Connections
{
    public class SQLDatabaseConnection : _BaseSQLConnection
    {

        public SQLDatabaseConnection() : base() { }

        public SQLDatabaseConnection(string Name) : base(Name)
        {
        }

        public SQLDatabaseConnection(string Name, string Data)
            : base(Name, Data)
        {}


        public override string Usage
        {
            get 
            {
                return Properties.Resources.SqlDatabaseConnection_Usage;
            }
        }
    
        public string InitialCatalog
        {
            get { return builder.InitialCatalog; }
            set
            {
                builder.InitialCatalog = value;
                base.Data = builder.ConnectionString;
                OnPropertyChanged("InitialCatalog");
            }
        }

        protected internal override bool performSQLConnectionTypeValidation(ref SqlConnection connection)
        {
            if (string.IsNullOrEmpty(InitialCatalog))
            {
                Debug.WriteLine("SQLDatabaseConnection requires a Catalog to be set");
                return false;
            }
            else
            {
                try
                {
                    SqlCommand cmd = connection.CreateCommand();
                    cmd.CommandText = "Select Count(1) from sys.databases where name='" + InitialCatalog + "'";
                    object result = cmd.ExecuteScalar();
                    if (result != null && result is int && (int)result == 1)
                    {
                        //OK database exist so change to it, and validate dbo access
                        connection.ChangeDatabase(InitialCatalog);
                        cmd = connection.CreateCommand();

                        cmd.CommandText = "SELECT IS_ROLEMEMBER('sysadmin')";
                        result = cmd.ExecuteScalar();
                        return (result != null && result is int && (int)result == 1);
                    }
                    else
                    {
                        //OK Database doesn't exist so let see if we can create one
                        cmd.CommandText = "SELECT IS_SRVROLEMEMBER('dbcreator')";
                        result = cmd.ExecuteScalar();
                        return (result != null && result is int && (int)result == 1);
                    }
                    
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    return false;
                }
            }
        }
      

    }
}
